package com.campusbackend.controller;

import com.campusbackend.entity.Result;
import com.campusbackend.entity.Teachers;
import com.campusbackend.entity.Students;
import com.campusbackend.entity.vo.NotificationConfirmVO;
import com.campusbackend.entity.vo.NotificationCreateVO;
import com.campusbackend.entity.vo.NotificationDetailVO;
import com.campusbackend.entity.vo.NotificationListVO;
import com.campusbackend.service.NotificationsService;
import com.campusbackend.service.TeachersService;
import com.campusbackend.service.StudentsService;
import com.campusbackend.utils.ResultUtil;
import com.campusbackend.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 队伍通知表 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-07-26
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/notifications")
@Tag(name = "队伍通知中心", description = "队伍通知中心相关接口")
public class NotificationsController {

    @Autowired
    private NotificationsService notificationsService;

    @Autowired
    private TeachersService teachersService;

    @Autowired
    private StudentsService studentsService;

    /**
     * 发布通知
     *
     * @param createVO 通知创建对象
     * @return 发布结果
     */
    @PostMapping("/publish")
    @Operation(summary = "发布通知", description = "在队伍中发布通知，支持文本和图片内容")
    public Result<String> publishNotification(@Valid @RequestBody NotificationCreateVO createVO) {
        // 获取当前登录用户信息
        Object[] userInfo = getCurrentUserInfo();
        Byte publisherType = (Byte) userInfo[0];
        Long userId = (Long) userInfo[1];
        String userName = (String) userInfo[2];

        log.info("发布通知请求 - 用户: {} ({}), 队伍ID: {}, 标题: {}, 图片列表: {}",
                userName, publisherType == 1 ? "教师" : "学生", createVO.getTeamId(), createVO.getTitle(), createVO.getImages());

        String result = notificationsService.publishNotification(createVO, publisherType, userId, userName);

        if ("通知发布成功".equals(result)) {
            return ResultUtil.success(result);
        } else {
            return ResultUtil.fail(result);
        }
    }

    /**
     * 获取队伍通知列表
     *
     * @param teamId 队伍ID
     * @return 通知列表
     */
    @GetMapping("/team/{teamId}")
    @Operation(summary = "获取队伍通知列表", description = "获取指定队伍的所有通知列表")
    public Result<List<NotificationListVO>> getTeamNotifications(@PathVariable Long teamId) {
        // 获取当前登录用户信息
        Object[] userInfo = getCurrentUserInfo();
        Byte currentUserType = (Byte) userInfo[0];
        Long userId = (Long) userInfo[1];

        log.info("获取队伍通知列表请求 - 用户: {} ({}), 队伍ID: {}",
                userId, currentUserType == 1 ? "教师" : "学生", teamId);

        List<NotificationListVO> notifications = notificationsService.getTeamNotifications(teamId, currentUserType, userId);

        return ResultUtil.success(notifications);
    }

    /**
     * 获取通知详情
     *
     * @param notificationId 通知ID
     * @return 通知详情
     */
    @GetMapping("/{notificationId}")
    @Operation(summary = "获取通知详情", description = "获取指定通知的详细信息，包括确认情况")
    public Result<NotificationDetailVO> getNotificationDetail(@PathVariable Long notificationId) {
        // 获取当前登录用户信息
        Object[] userInfo = getCurrentUserInfo();
        Byte currentUserType = (Byte) userInfo[0];
        Long userId = (Long) userInfo[1];

        log.info("获取通知详情请求 - 用户: {} ({}), 通知ID: {}",
                userId, currentUserType == 1 ? "教师" : "学生", notificationId);

        NotificationDetailVO detail = notificationsService.getNotificationDetail(notificationId, currentUserType, userId);

        if (detail != null) {
            return ResultUtil.success(detail);
        } else {
            return ResultUtil.fail("通知不存在或您无权查看");
        }
    }

    /**
     * 确认通知
     *
     * @param confirmVO 确认对象
     * @return 确认结果
     */
    @PostMapping("/confirm")
    @Operation(summary = "确认通知", description = "确认已阅读通知，可添加备注")
    public Result<String> confirmNotification(@Valid @RequestBody NotificationConfirmVO confirmVO) {
        // 获取当前登录用户信息
        Object[] userInfo = getCurrentUserInfo();
        Byte confirmerType = (Byte) userInfo[0];
        Long userId = (Long) userInfo[1];
        String userName = (String) userInfo[2];

        log.info("确认通知请求 - 用户: {} ({}), 通知ID: {}",
                userName, confirmerType == 1 ? "教师" : "学生", confirmVO.getNotificationId());

        String result = notificationsService.confirmNotification(confirmVO, confirmerType, userId, userName);

        if ("确认成功".equals(result)) {
            return ResultUtil.success(result);
        } else {
            return ResultUtil.fail(result);
        }
    }

    /**
     * 删除通知
     *
     * @param notificationId 通知ID
     * @return 删除结果
     */
    @DeleteMapping("/{notificationId}")
    @Operation(summary = "删除通知", description = "删除通知（仅发布者可删除）")
    public Result<String> deleteNotification(@PathVariable Long notificationId) {
        // 获取当前登录用户信息
        Object[] userInfo = getCurrentUserInfo();
        Byte currentUserType = (Byte) userInfo[0];
        Long userId = (Long) userInfo[1];

        log.info("删除通知请求 - 用户: {} ({}), 通知ID: {}",
                userId, currentUserType == 1 ? "教师" : "学生", notificationId);

        String result = notificationsService.deleteNotification(notificationId, currentUserType, userId);

        if ("删除成功".equals(result)) {
            return ResultUtil.success(result);
        } else {
            return ResultUtil.fail(result);
        }
    }

    /**
     * 获取当前用户信息
     *
     * @return 用户信息数组 [userType, userId, userName]
     */
    private Object[] getCurrentUserInfo() {
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        String userType = (String) userInfo.get("userType");
        Long userId = ((Number) userInfo.get("id")).longValue();

        String userName = "";
        if ("teacher".equals(userType)) {
            Teachers teacher = teachersService.getById(userId);
            userName = teacher != null ? teacher.getRealName() : "";
        } else if ("student".equals(userType)) {
            Students student = studentsService.getById(userId);
            userName = student != null ? student.getRealName() : "";
        }

        Byte userTypeCode = "teacher".equals(userType) ? (byte) 1 : (byte) 2;

        return new Object[]{userTypeCode, userId, userName};
    }

    /**
     * 获取通知确认名单
     *
     * @param notificationId 通知ID
     * @return 确认名单
     */
    @GetMapping("/{notificationId}/confirmations")
    @Operation(summary = "获取通知确认名单", description = "获取指定通知的确认名单，包括已确认和未确认成员")
    public Result<Map<String, Object>> getNotificationConfirmations(@PathVariable Long notificationId) {
        // 获取当前登录用户信息
        Object[] userInfo = getCurrentUserInfo();
        Byte currentUserType = (Byte) userInfo[0];
        Long userId = (Long) userInfo[1];

        log.info("获取通知确认名单请求 - 用户: {} ({}), 通知ID: {}",
                userId, currentUserType == 1 ? "教师" : "学生", notificationId);

        NotificationDetailVO detail = notificationsService.getNotificationDetail(notificationId, currentUserType, userId);

        if (detail != null) {
            Map<String, Object> confirmationData = new HashMap<>();
            confirmationData.put("notificationId", notificationId);
            confirmationData.put("title", detail.getTitle());
            confirmationData.put("requireConfirmation", detail.getRequireConfirmation());
            confirmationData.put("totalMembers", detail.getTotalMembers());
            confirmationData.put("confirmedCount", detail.getConfirmedCount());
            confirmationData.put("confirmationProgress",
                detail.getTotalMembers() > 0 ? (double) detail.getConfirmedCount() / detail.getTotalMembers() * 100 : 0.0);
            confirmationData.put("confirmedMembers", detail.getConfirmations());
            confirmationData.put("unconfirmedMembers", detail.getUnconfirmedMembers());

            return ResultUtil.success(confirmationData);
        } else {
            return ResultUtil.fail("通知不存在或您无权查看");
        }
    }
}